import datetime
import jwt
from flask import Flask, request, jsonify, abort, g
from config.config import Config
from functools import wraps


def generate_token(user_id):
    payload = {
        'user_id': user_id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24 * 365)  # Token 1小时后过期
    }
    return jwt.encode(payload, Config.LOGING_SECRET_KEY, algorithm='HS256')


def decode_token(token):
    try:
        return jwt.decode(token, Config.LOGING_SECRET_KEY, algorithms=['HS256'])
    except jwt.ExpiredSignatureError:
        return jsonify({
            'data': {},
            'message': 'Token expired. Please login again.',
            'status': 500
        })
    except jwt.InvalidTokenError:
        jsonify({
            'data': {},
            'message': 'Invalid token. Please login again.',
            'status': 500
        })

def token_required(f):
    @wraps(f)
    def decorator(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({
                'data': {},
                'message': 'Token is missing',
                'status': 500
            })
        try:
            # 这里解码 token 并把用户信息存储到 `g` 对象中
            decoded = decode_token(token)
            g.user_id = decoded['user_id']
        except Exception as e:
            return jsonify({
                'data': {},
                'message': 'Token is error',
                'status': 500
            })

        return f(*args, **kwargs)

    return decorator
